package com.zhongkai;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author 某家:
 * @version
 * 类说明
 */
public class Connect {
    private  final ThreadLocal<Socket> threadConnect = new ThreadLocal<Socket>();

    private  final String HOST = "127.0.0.1";

    private  final int PORT = 9001;

    private  String is_succeed = "001";

    private  Socket client;

    private  OutputStream outStr = null;

    private  InputStream inStr = null;

    //public  Thread tRecv = new Thread(new RecvThread());
    // private  Thread tKeep = new Thread(new KeepThread());


    public void connect() throws UnknownHostException, IOException {
        client = threadConnect.get();
        if (client == null) {
            client = new Socket(HOST, PORT);
            threadConnect.set(client);
            //  tKeep.start();
            System.out.println("======== 链接开始！========");
        }
        outStr = client.getOutputStream();
        inStr = client.getInputStream();

    }

    public  void disconnect() {
        try {
            outStr.close();  //
            inStr.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public String newMessage(String ip) {
        try {
            System.out.println("==============接收信息===============");
            while (true) {
                byte[] b = new byte[1024];
                int r = inStr.read(b);
                if (r > -1) {
                    String str = new String(b, "UTF-8");
                    System.out.println(str);
                    if (str.contains("A1")) {
                        // disconnect();
                        //查询设备ip

                        outStr.write(("facility_ip&"+ip).getBytes("UTF-8"));
                    } else if (str.contains("device_ok")) {

                        disconnect();
                        return "device_ok";

                    }else if (str.contains("device_error")){
                        disconnect();
                        return "device_error";
                    }
                }
            }
        } catch (IOException e) {

            e.printStackTrace();
            return "执行失败";
        }
    }




/*    public  void main(String[] args) {
        try {
            Connect.connect();
            tRecv.start();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }*/

    public String getIs_succeed() {
        return is_succeed;
    }

    public void setIs_succeed(String is_succeed) {
        this.is_succeed = is_succeed;
    }
}